#!/bin/bash
#
# Linux 自动部署脚本
# 适用于 Ubuntu 20.04+ / CentOS 7+
#

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  股票分析后端 - Linux自动部署脚本${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 检测操作系统
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
    VERSION=$VERSION_ID
else
    echo -e "${RED}无法检测操作系统${NC}"
    exit 1
fi

echo -e "${YELLOW}检测到操作系统: $OS $VERSION${NC}"
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}请使用root权限运行此脚本: sudo ./deploy.sh${NC}"
    exit 1
fi

# 询问部署模式
echo "请选择部署模式:"
echo "1) 生产环境（Systemd + Gunicorn + Nginx）- 推荐"
echo "2) 开发环境（直接运行）"
echo "3) Docker部署"
read -p "请输入选项 [1-3]: " DEPLOY_MODE

# 询问是否跳过数据库配置
echo ""
read -p "是否跳过数据库配置？(y/N): " SKIP_DB
SKIP_DB=${SKIP_DB:-n}

# 询问是否使用国内镜像源
echo ""
echo "选择pip镜像源（加速依赖下载）:"
echo "1) 清华大学（推荐）"
echo "2) 阿里云"
echo "3) 中国科技大学"
echo "4) 豆瓣"
echo "5) 官方源（默认，速度较慢）"
read -p "请输入选项 [1-5]: " PIP_MIRROR_CHOICE

case $PIP_MIRROR_CHOICE in
    1)
        PIP_MIRROR="https://pypi.tuna.tsinghua.edu.cn/simple"
        PIP_MIRROR_NAME="清华大学"
        ;;
    2)
        PIP_MIRROR="https://mirrors.aliyun.com/pypi/simple/"
        PIP_MIRROR_NAME="阿里云"
        ;;
    3)
        PIP_MIRROR="https://pypi.mirrors.ustc.edu.cn/simple/"
        PIP_MIRROR_NAME="中国科技大学"
        ;;
    4)
        PIP_MIRROR="https://pypi.douban.com/simple/"
        PIP_MIRROR_NAME="豆瓣"
        ;;
    *)
        PIP_MIRROR=""
        PIP_MIRROR_NAME="官方源"
        ;;
esac

if [ -n "$PIP_MIRROR" ]; then
    echo -e "${GREEN}已选择: $PIP_MIRROR_NAME 镜像源${NC}"
    PIP_INDEX_OPTION="-i $PIP_MIRROR"
else
    echo -e "${YELLOW}使用官方源${NC}"
    PIP_INDEX_OPTION=""
fi

# 配置参数
if [[ "$SKIP_DB" != "y" && "$SKIP_DB" != "Y" ]]; then
read -p "请输入MySQL root密码: " -s MYSQL_ROOT_PASSWORD
echo ""
read -p "请输入应用数据库密码: " -s DB_PASSWORD
echo ""
else
    echo -e "${YELLOW}将跳过MySQL/MariaDB配置${NC}"
    DB_PASSWORD="stockapp123"  # 默认密码，需要手动配置.env
fi

read -p "请输入服务器IP或域名: " SERVER_DOMAIN
echo ""

APP_USER="stockapp"
APP_DIR="/home/$APP_USER/stock-backend"
VENV_DIR="$APP_DIR/venv"

# ========================================
# 1. 安装系统依赖
# ========================================
echo -e "${GREEN}[1/8] 安装系统依赖...${NC}"

# 检查并清理包管理器锁（针对 CentOS/RHEL 系列）
if [[ "$OS" == "centos" ]] || [[ "$OS" == "rhel" ]] || [[ "$OS" == "opencloudos" ]] || [[ "$OS" == "tencentos" ]]; then
    echo -e "${YELLOW}检查包管理器锁...${NC}"
    
    # 等待其他包管理器进程完成（最多等待30秒）
    WAIT_COUNT=0
    while pidof yum dnf >/dev/null && [ $WAIT_COUNT -lt 6 ]; do
        echo -e "${YELLOW}检测到其他包管理器进程正在运行，等待中...${NC}"
        sleep 5
        WAIT_COUNT=$((WAIT_COUNT + 1))
    done
    
    # 如果还在运行，强制清理
    if pidof yum dnf >/dev/null; then
        echo -e "${YELLOW}强制清理包管理器锁...${NC}"
        killall -9 yum dnf 2>/dev/null || true
        rm -f /var/run/yum.pid /var/lib/rpm/.rpm.lock 2>/dev/null || true
        rm -rf /var/lib/dnf/locks/* 2>/dev/null || true
        sleep 2
    fi
fi

if [[ "$OS" == "ubuntu" ]] || [[ "$OS" == "debian" ]]; then
    apt update -y
    
    # 基础包
    BASE_PACKAGES="python3.9 python3.9-venv python3-pip redis-server build-essential wget nginx git curl"
    
    # 如果不跳过数据库配置，安装 MySQL
    if [[ "$SKIP_DB" != "y" && "$SKIP_DB" != "Y" ]]; then
        apt install -y $BASE_PACKAGES mysql-server
    DB_SERVICE="mysql"
    else
        apt install -y $BASE_PACKAGES
        echo -e "${YELLOW}跳过MySQL安装${NC}"
    fi
    
    PYTHON_CMD="python3.9"
elif [[ "$OS" == "centos" ]] || [[ "$OS" == "rhel" ]] || [[ "$OS" == "opencloudos" ]] || [[ "$OS" == "tencentos" ]]; then
    yum clean all
    
    # 安装 EPEL 仓库（用于 nginx 和其他软件）
    yum install -y epel-release 2>/dev/null || yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm 2>/dev/null || true
    
    # OpenCloudOS 9+ 使用不同的包名
    if [[ "$OS" == "opencloudos" ]] || [[ "$OS" == "tencentos" ]]; then
        yum update -y --allowerasing --nobest
        # OpenCloudOS 使用 python3 和 python3-devel
        yum install -y --allowerasing --nobest python3 python3-devel python3-pip redis git wget curl gcc gcc-c++ make
        
        # 如果不跳过数据库配置，安装数据库
        if [[ "$SKIP_DB" != "y" && "$SKIP_DB" != "Y" ]]; then
        # OpenCloudOS 通常使用 MariaDB 代替 MySQL（完全兼容）
        echo -e "${YELLOW}尝试安装数据库...${NC}"
        if ! yum install -y mysql-server 2>/dev/null; then
            echo -e "${YELLOW}MySQL 不可用，使用 MariaDB（完全兼容）${NC}"
            yum install -y mariadb-server mariadb
            # 创建 mysql 命令的软链接
            ln -sf /usr/bin/mariadb /usr/bin/mysql 2>/dev/null || true
            ln -sf /usr/bin/mariadb-admin /usr/bin/mysqladmin 2>/dev/null || true
            # 使用 MariaDB 服务
            DB_SERVICE="mariadb"
        else
            DB_SERVICE="mysqld"
            fi
        else
            echo -e "${YELLOW}跳过MySQL/MariaDB安装${NC}"
        fi
        
        # 尝试从 EPEL 安装 nginx，如果失败则跳过（后面手动安装）
        yum install -y nginx 2>/dev/null || echo -e "${YELLOW}Nginx 将稍后安装${NC}"
    else
        # CentOS 7/8
        yum update -y --allowerasing --nobest
        
        # 基础包
        BASE_PKGS="python39 python39-devel redis nginx git wget curl gcc gcc-c++ make"
        
        if [[ "$SKIP_DB" != "y" && "$SKIP_DB" != "Y" ]]; then
            yum install -y --allowerasing --nobest $BASE_PKGS mysql-server
        DB_SERVICE="mysqld"
        else
            yum install -y --allowerasing --nobest $BASE_PKGS
            echo -e "${YELLOW}跳过MySQL安装${NC}"
        fi
    fi
else
    echo -e "${RED}不支持的操作系统: $OS${NC}"
    exit 1
fi

# 创建 python3 的符号链接（确保兼容性）
if ! command -v python3.9 &> /dev/null; then
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
        echo -e "${YELLOW}使用系统 Python: $(python3 --version)${NC}"
    else
        echo -e "${RED}未找到 Python 3，安装失败${NC}"
        exit 1
    fi
else
    PYTHON_CMD="python3.9"
fi

# ========================================
# 2. 安装TA-Lib
# ========================================
echo -e "${GREEN}[2/8] 安装TA-Lib技术指标库...${NC}"

# 检查是否已安装
if [ -f /usr/lib/libta_lib.so ] || [ -f /usr/local/lib/libta_lib.so ] || [ -f /usr/lib64/libta_lib.so ]; then
    echo -e "${YELLOW}TA-Lib 已安装，跳过${NC}"
else
    # 确保编译依赖已安装
    echo -e "${YELLOW}检查编译依赖...${NC}"
    if [[ "$OS" == "ubuntu" ]] || [[ "$OS" == "debian" ]]; then
        apt install -y build-essential autoconf automake libtool
    else
        yum install -y gcc gcc-c++ make autoconf automake libtool
    fi
    
    cd /tmp
    echo -e "${YELLOW}正在下载 TA-Lib...${NC}"
    
    # 清理旧的下载文件
    rm -rf /tmp/ta-lib* 2>/dev/null
    
    # 尝试多个下载源
    if ! wget --progress=bar:force --timeout=60 --tries=3 \
        http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz 2>/dev/null; then
        echo -e "${YELLOW}尝试备用下载源...${NC}"
        if ! wget --progress=bar:force --timeout=60 --tries=3 \
            https://github.com/TA-Lib/ta-lib/releases/download/v0.4.0/ta-lib-0.4.0-src.tar.gz 2>/dev/null; then
            echo -e "${RED}TA-Lib 下载失败！${NC}"
            echo -e "${YELLOW}请手动安装 TA-Lib 或使用 Docker 部署${NC}"
            echo -e "${YELLOW}手动安装命令：${NC}"
            echo "  wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz"
            echo "  tar -xzf ta-lib-0.4.0-src.tar.gz"
            echo "  cd ta-lib/"
            echo "  ./configure --prefix=/usr"
            echo "  make"
            echo "  sudo make install"
            exit 1
        fi
    fi
    
    echo -e "${YELLOW}正在解压...${NC}"
    tar -xzf ta-lib-0.4.0-src.tar.gz
    cd ta-lib/
    
    echo -e "${YELLOW}正在配置（约1-2分钟）...${NC}"
    if ! ./configure --prefix=/usr; then
        echo -e "${RED}配置失败！${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}正在编译（约3-5分钟，请耐心等待）...${NC}"
    # 先尝试单线程编译（更稳定）
    if ! make; then
        echo -e "${RED}编译失败！尝试清理后重新编译...${NC}"
        make clean
        if ! make -j1; then
            echo -e "${RED}TA-Lib 编译失败！${NC}"
            echo -e "${YELLOW}这可能是由于：${NC}"
            echo "  1. 缺少编译工具（gcc, g++, make）"
            echo "  2. 系统内存不足"
            echo "  3. 磁盘空间不足"
            echo ""
            echo -e "${YELLOW}建议：${NC}"
            echo "  1. 检查系统资源: free -h && df -h"
            echo "  2. 使用 Docker 部署（选项3）"
            echo "  3. 使用预编译的 Python wheel 包"
            cd /tmp
            rm -rf /tmp/ta-lib*
            exit 1
        fi
    fi
    
    echo -e "${YELLOW}正在安装...${NC}"
    if ! make install; then
        echo -e "${RED}安装失败！${NC}"
        exit 1
    fi
    
    # 更新动态链接库缓存
    ldconfig
    
    # 验证安装
    if [ -f /usr/lib/libta_lib.so ] || [ -f /usr/local/lib/libta_lib.so ] || [ -f /usr/lib64/libta_lib.so ]; then
        echo -e "${GREEN}TA-Lib 安装成功${NC}"
    else
        echo -e "${RED}TA-Lib 安装验证失败！${NC}"
        exit 1
    fi
    
    cd ~
    rm -rf /tmp/ta-lib*
fi

# ========================================
# 3. 配置MySQL/MariaDB
# ========================================
echo -e "${GREEN}[3/8] 配置MySQL/MariaDB数据库...${NC}"

if [[ "$SKIP_DB" == "y" || "$SKIP_DB" == "Y" ]]; then
    echo -e "${YELLOW}跳过数据库配置（根据用户选择）${NC}"
    echo -e "${YELLOW}请确保：${NC}"
    echo "  1. MySQL/MariaDB 已安装并运行"
    echo "  2. 数据库 'stock_analysis' 已创建"
    echo "  3. 用户 '$APP_USER' 已创建并有相应权限"
    echo "  4. 稍后需要手动配置 .env 文件中的数据库密码"
else
# 使用动态检测的数据库服务名
systemctl start $DB_SERVICE || systemctl start mysql || systemctl start mysqld
systemctl enable $DB_SERVICE || systemctl enable mysql || systemctl enable mysqld

    # 等待MySQL完全启动
    echo -e "${YELLOW}等待数据库服务启动...${NC}"
    sleep 3

    # 尝试多种方式连接MySQL
    DB_CONNECT_SUCCESS=false
    
    # 方式1: 尝试使用sudo（适用于MariaDB和新版MySQL的unix_socket认证）
    echo -e "${YELLOW}尝试使用系统认证连接数据库...${NC}"
    if sudo mysql -e "SELECT 1;" &>/dev/null; then
        echo -e "${GREEN}使用sudo连接成功${NC}"
        sudo mysql <<MYSQL_SCRIPT
-- 设置root密码
ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';
-- 创建数据库
CREATE DATABASE IF NOT EXISTS stock_analysis CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建应用用户
CREATE USER IF NOT EXISTS '$APP_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON stock_analysis.* TO '$APP_USER'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT
        DB_CONNECT_SUCCESS=true
    
    # 方式2: 尝试无密码连接（全新安装）
    elif mysql -u root -e "SELECT 1;" &>/dev/null; then
        echo -e "${GREEN}无密码连接成功${NC}"
mysql -u root <<MYSQL_SCRIPT
ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';
CREATE DATABASE IF NOT EXISTS stock_analysis CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$APP_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON stock_analysis.* TO '$APP_USER'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT
        DB_CONNECT_SUCCESS=true
    
    # 方式3: 使用用户输入的root密码
    elif mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "SELECT 1;" &>/dev/null; then
        echo -e "${GREEN}使用提供的密码连接成功${NC}"
        mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<MYSQL_SCRIPT
CREATE DATABASE IF NOT EXISTS stock_analysis CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$APP_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON stock_analysis.* TO '$APP_USER'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT
        DB_CONNECT_SUCCESS=true
    
    # 方式4: 提示用户手动输入密码
    else
        echo -e "${YELLOW}自动连接失败，请手动输入MySQL root密码：${NC}"
        mysql -u root -p <<MYSQL_SCRIPT
ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';
CREATE DATABASE IF NOT EXISTS stock_analysis CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$APP_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON stock_analysis.* TO '$APP_USER'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT
        
        if [ $? -eq 0 ]; then
            DB_CONNECT_SUCCESS=true
        fi
    fi
    
    if [ "$DB_CONNECT_SUCCESS" = true ]; then
echo -e "${GREEN}MySQL配置完成${NC}"
    else
        echo -e "${RED}数据库配置失败！${NC}"
        echo -e "${YELLOW}请手动配置数据库或重新运行脚本选择跳过数据库配置${NC}"
        echo ""
        echo -e "${YELLOW}手动配置命令：${NC}"
        echo "sudo mysql  # 或 mysql -u root -p"
        echo "CREATE DATABASE IF NOT EXISTS stock_analysis CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
        echo "CREATE USER IF NOT EXISTS '$APP_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';"
        echo "GRANT ALL PRIVILEGES ON stock_analysis.* TO '$APP_USER'@'localhost';"
        echo "FLUSH PRIVILEGES;"
        echo "EXIT;"
        exit 1
    fi
fi

# ========================================
# 4. 配置Redis
# ========================================
echo -e "${GREEN}[4/8] 配置Redis缓存...${NC}"

systemctl start redis || systemctl start redis-server
systemctl enable redis || systemctl enable redis-server

echo -e "${GREEN}Redis配置完成${NC}"

# ========================================
# 5. 创建应用用户和目录
# ========================================
echo -e "${GREEN}[5/8] 创建应用用户...${NC}"

if ! id "$APP_USER" &>/dev/null; then
    useradd -m -s /bin/bash $APP_USER
    echo -e "${GREEN}用户 $APP_USER 创建成功${NC}"
else
    echo -e "${YELLOW}用户 $APP_USER 已存在${NC}"
fi

# 复制应用文件
mkdir -p $APP_DIR

# 获取脚本所在目录（backend目录）
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

echo -e "${YELLOW}从 $SCRIPT_DIR 复制文件到 $APP_DIR${NC}"
cp -r "$SCRIPT_DIR"/* $APP_DIR/ 2>/dev/null || cp -r ./* $APP_DIR/

# 验证关键文件
if [ ! -f "$APP_DIR/main.py" ]; then
    echo -e "${RED}错误: main.py 文件未找到！${NC}"
    echo -e "${YELLOW}请确保在 backend 目录中运行此脚本${NC}"
    exit 1
fi

chown -R $APP_USER:$APP_USER $APP_DIR

# ========================================
# 6. 安装Python依赖
# ========================================
echo -e "${GREEN}[6/8] 安装Python依赖...${NC}"

# 创建虚拟环境并升级pip
echo -e "${YELLOW}使用镜像源: $PIP_MIRROR_NAME${NC}"

su - $APP_USER <<EOF
cd ~/stock-backend
$PYTHON_CMD -m venv venv
source venv/bin/activate
pip install --upgrade pip setuptools wheel $PIP_INDEX_OPTION
EOF

# 创建临时脚本来安装依赖（容错模式）
cat > /tmp/install_deps.sh << INSTALL_SCRIPT
#!/bin/bash
source ~/stock-backend/venv/bin/activate
cd ~/stock-backend

# pip镜像配置
PIP_INDEX_OPT="$PIP_INDEX_OPTION"

echo "========================================="
echo "开始逐个安装Python依赖（容错模式）"
if [ -n "\$PIP_INDEX_OPT" ]; then
    echo "使用镜像源: $PIP_MIRROR_NAME"
fi
echo "========================================="

FAILED_PACKAGES=()
INSTALLED_PACKAGES=()

# 读取requirements.txt并逐行安装
while IFS= read -r line || [ -n "\$line" ]; do
    # 跳过空行和注释
    if [[ -z "\$line" ]] || [[ "\$line" =~ ^[[:space:]]*# ]]; then
        continue
    fi
    
    # 提取包名（去掉版本号）
    package=\$(echo "\$line" | sed 's/[>=<~!].*//' | xargs)
    
    echo "----------------------------------------"
    echo "正在安装: \$line"
    
    # 尝试安装
    if pip install "\$line" \$PIP_INDEX_OPT 2>&1 | tee /tmp/pip_install.log; then
        echo "✓ 成功: \$package"
        INSTALLED_PACKAGES+=("\$package")
    else
        echo "✗ 失败: \$package"
        FAILED_PACKAGES+=("\$package")
        
        # 对于ta-lib，尝试不同的安装方式
        if [[ "\$package" == "ta-lib" ]] || [[ "\$package" == "TA-Lib" ]]; then
            echo "尝试备用方案安装 TA-Lib..."
            if pip install TA-Lib --no-cache-dir --prefer-binary \$PIP_INDEX_OPT 2>/dev/null; then
                echo "✓ TA-Lib 备用方案成功"
                INSTALLED_PACKAGES+=("ta-lib")
                FAILED_PACKAGES=("\${FAILED_PACKAGES[@]/\$package}")
            else
                echo "⚠ TA-Lib 所有安装方式都失败，请稍后手动安装"
            fi
        fi
    fi
done < requirements.txt

# 安装gunicorn（生产环境必需）
echo "----------------------------------------"
echo "正在安装 Gunicorn（生产服务器）..."
if pip install gunicorn \$PIP_INDEX_OPT; then
    echo "✓ Gunicorn 安装成功"
    INSTALLED_PACKAGES+=("gunicorn")
else
    echo "✗ Gunicorn 安装失败"
    FAILED_PACKAGES+=("gunicorn")
fi

# 显示安装总结
echo "========================================="
echo "依赖安装总结"
echo "========================================="
echo "成功安装: \${#INSTALLED_PACKAGES[@]} 个包"
echo "失败: \${#FAILED_PACKAGES[@]} 个包"

if [ \${#FAILED_PACKAGES[@]} -gt 0 ]; then
    echo ""
    echo "⚠ 以下包安装失败："
    for pkg in "\${FAILED_PACKAGES[@]}"; do
        echo "  - \$pkg"
    done
    echo ""
    echo "提示："
    echo "  1. TA-Lib 需要先安装系统库（libta_lib.so）"
    echo "  2. 某些包可能需要额外的系统依赖"
    echo "  3. 可以稍后手动安装: pip install <package-name> \$PIP_INDEX_OPT"
    echo ""
fi

# 验证关键依赖
echo "验证关键依赖..."
python -c "import fastapi; print('✓ FastAPI 可用')" 2>/dev/null || echo "✗ FastAPI 不可用"
python -c "import uvicorn; print('✓ Uvicorn 可用')" 2>/dev/null || echo "✗ Uvicorn 不可用"
python -c "import sqlalchemy; print('✓ SQLAlchemy 可用')" 2>/dev/null || echo "✗ SQLAlchemy 不可用"
python -c "import pandas; print('✓ Pandas 可用')" 2>/dev/null || echo "✗ Pandas 不可用"
python -c "import talib; print('✓ TA-Lib 可用')" 2>/dev/null || echo "⚠ TA-Lib 不可用（技术指标功能可能受限）"

echo "========================================="

# 如果关键包失败，退出
if [[ " \${FAILED_PACKAGES[@]} " =~ " fastapi " ]] || [[ " \${FAILED_PACKAGES[@]} " =~ " uvicorn " ]]; then
    echo "✗ 关键依赖安装失败，无法继续"
    exit 1
fi

exit 0
INSTALL_SCRIPT

chmod +x /tmp/install_deps.sh
chown $APP_USER:$APP_USER /tmp/install_deps.sh

# 执行安装脚本
if su - $APP_USER -c "/tmp/install_deps.sh"; then
    echo -e "${GREEN}Python依赖安装完成${NC}"
else
    echo -e "${YELLOW}部分依赖安装失败，但关键组件已安装${NC}"
fi

# 清理临时脚本
rm -f /tmp/install_deps.sh /tmp/pip_install.log

# ========================================
# 7. 配置环境变量
# ========================================
echo -e "${GREEN}[7/8] 配置环境变量...${NC}"

cat > $APP_DIR/.env << EOF
# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_USER=$APP_USER
DB_PASSWORD=$DB_PASSWORD
DB_NAME=stock_analysis

# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0

# API配置
API_HOST=0.0.0.0
API_PORT=8000
API_DEBUG=False

# 缓存配置
CACHE_EXPIRE_SECONDS=300

# 日志配置
LOG_LEVEL=INFO
EOF

chmod 600 $APP_DIR/.env
chown $APP_USER:$APP_USER $APP_DIR/.env

# 初始化数据库
if [[ "$SKIP_DB" == "y" || "$SKIP_DB" == "Y" ]]; then
    echo -e "${YELLOW}跳过数据库初始化${NC}"
    echo -e "${YELLOW}稍后需要手动运行: python database.py${NC}"
else
    echo -e "${GREEN}正在初始化数据库表...${NC}"
su - $APP_USER <<EOF
cd ~/stock-backend
source venv/bin/activate
python database.py
EOF
    echo -e "${GREEN}数据库初始化完成${NC}"
fi

# ========================================
# 8. 根据模式部署
# ========================================

if [ "$DEPLOY_MODE" == "1" ]; then
    # 生产环境部署
    echo -e "${GREEN}[8/8] 配置Systemd服务...${NC}"
    
    # 创建日志目录
    mkdir -p /var/log/stock-backend
    chown $APP_USER:$APP_USER /var/log/stock-backend
    
    # 创建systemd服务
    cat > /etc/systemd/system/stock-backend.service << EOF
[Unit]
Description=Stock Analysis Backend API
After=network.target $DB_SERVICE.service redis.service
Requires=$DB_SERVICE.service redis.service

[Service]
Type=notify
User=$APP_USER
Group=$APP_USER
WorkingDirectory=$APP_DIR
Environment="PATH=$VENV_DIR/bin"
ExecStart=$VENV_DIR/bin/gunicorn \\
    -k uvicorn.workers.UvicornWorker \\
    -w 4 \\
    --bind 0.0.0.0:8000 \\
    --timeout 120 \\
    --access-logfile /var/log/stock-backend/access.log \\
    --error-logfile /var/log/stock-backend/error.log \\
    main:app

Restart=always
RestartSec=10
KillMode=mixed
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
EOF

    # 配置Nginx
    echo -e "${YELLOW}配置Nginx反向代理...${NC}"
    
    # 检测Nginx安装路径
    if [ -d "/www/server/nginx" ]; then
        # 宝塔面板/LNMP一键包安装的Nginx
        echo -e "${YELLOW}检测到宝塔面板/LNMP环境${NC}"
        NGINX_CONF_DIR="/www/server/panel/vhost/nginx"
        NGINX_LOG_DIR="/www/wwwlogs"
        NGINX_BIN="/www/server/nginx/sbin/nginx"
        
        # 如果vhost目录不存在，使用标准conf目录
        if [ ! -d "$NGINX_CONF_DIR" ]; then
            NGINX_CONF_DIR="/www/server/nginx/conf/vhost"
            mkdir -p $NGINX_CONF_DIR
        fi
        
        NGINX_CONF_FILE="$NGINX_CONF_DIR/stock-backend.conf"
        NGINX_ENABLE_CMD=""
        NGINX_TEST_CMD="$NGINX_BIN -t"
        NGINX_RELOAD_CMD="$NGINX_BIN -s reload"
        
    elif [[ "$OS" == "ubuntu" ]] || [[ "$OS" == "debian" ]]; then
        # Ubuntu/Debian 使用 sites-available/sites-enabled
        mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled
        NGINX_CONF_FILE="/etc/nginx/sites-available/stock-backend"
        NGINX_ENABLE_CMD="ln -sf /etc/nginx/sites-available/stock-backend /etc/nginx/sites-enabled/"
        NGINX_LOG_DIR="/var/log/stock-backend"
        NGINX_TEST_CMD="nginx -t"
        NGINX_RELOAD_CMD="systemctl reload nginx"
        
    else
        # CentOS/RHEL/OpenCloudOS 使用 conf.d
        mkdir -p /etc/nginx/conf.d
        NGINX_CONF_FILE="/etc/nginx/conf.d/stock-backend.conf"
        NGINX_ENABLE_CMD=""
        NGINX_LOG_DIR="/var/log/stock-backend"
        NGINX_TEST_CMD="nginx -t"
        NGINX_RELOAD_CMD="systemctl reload nginx"
    fi
    
    # 确保日志目录存在
    mkdir -p $NGINX_LOG_DIR
    chown -R $APP_USER:$APP_USER $NGINX_LOG_DIR 2>/dev/null || true
    
    # 创建Nginx配置文件
    cat > $NGINX_CONF_FILE << EOF
upstream stock_backend {
    server 127.0.0.1:8000;
}

server {
    listen 80;
    server_name $SERVER_DOMAIN;

    client_max_body_size 10M;
    
    # 访问日志和错误日志
    access_log $NGINX_LOG_DIR/stock-backend-access.log;
    error_log $NGINX_LOG_DIR/stock-backend-error.log;

    location / {
        proxy_pass http://stock_backend;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOF

    # 启用Nginx配置（仅Ubuntu/Debian需要）
    if [ -n "$NGINX_ENABLE_CMD" ]; then
        eval $NGINX_ENABLE_CMD
    fi
    
    echo -e "${GREEN}Nginx配置文件已创建: $NGINX_CONF_FILE${NC}"
    
    # 启动后端服务
    systemctl daemon-reload
    systemctl start stock-backend
    systemctl enable stock-backend
    
    # 测试并重载Nginx配置
    echo -e "${YELLOW}测试Nginx配置...${NC}"
    if $NGINX_TEST_CMD; then
        echo -e "${GREEN}Nginx配置测试通过${NC}"
        if [ -d "/www/server/nginx" ]; then
            # 宝塔面板使用reload
            $NGINX_RELOAD_CMD
            echo -e "${GREEN}Nginx已重载配置${NC}"
        else
            # 系统安装的Nginx使用systemctl
            systemctl restart nginx
            systemctl enable nginx
            echo -e "${GREEN}Nginx已重启${NC}"
        fi
    else
        echo -e "${RED}Nginx配置测试失败！${NC}"
        echo -e "${YELLOW}请手动检查配置: $NGINX_CONF_FILE${NC}"
    fi
    
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}部署完成！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "访问地址: ${YELLOW}http://$SERVER_DOMAIN${NC}"
    echo -e "API文档: ${YELLOW}http://$SERVER_DOMAIN/docs${NC}"
    echo -e "健康检查: ${YELLOW}http://$SERVER_DOMAIN/health${NC}"
    echo ""
    echo "常用命令:"
    echo "  查看状态: sudo systemctl status stock-backend"
    echo "  查看应用日志: sudo journalctl -u stock-backend -f"
    echo "  查看Nginx日志: sudo tail -f $NGINX_LOG_DIR/stock-backend-access.log"
    echo "  查看错误日志: sudo tail -f $NGINX_LOG_DIR/stock-backend-error.log"
    echo "  重启服务: sudo systemctl restart stock-backend"
    if [ -d "/www/server/nginx" ]; then
        echo "  重载Nginx: $NGINX_RELOAD_CMD"
    else
        echo "  重启Nginx: sudo systemctl restart nginx"
    fi
    echo ""
    echo "配置文件路径:"
    echo "  Nginx配置: $NGINX_CONF_FILE"
    echo "  应用配置: $APP_DIR/.env"
    echo "  日志目录: $NGINX_LOG_DIR"
    echo ""
    if [ -n "$PIP_MIRROR" ]; then
        echo -e "pip镜像源: ${YELLOW}$PIP_MIRROR_NAME${NC}"
        echo "  如需手动安装包: pip install <package> $PIP_INDEX_OPTION"
        echo ""
    fi
    
elif [ "$DEPLOY_MODE" == "2" ]; then
    # 开发环境
    echo -e "${GREEN}[8/8] 开发环境配置完成${NC}"
    echo ""
    echo -e "${YELLOW}启动服务:${NC}"
    echo "  cd $APP_DIR"
    echo "  source venv/bin/activate"
    echo "  python3 main.py"
    echo ""
    if [ -n "$PIP_MIRROR" ]; then
        echo -e "pip镜像源: ${YELLOW}$PIP_MIRROR_NAME${NC}"
        echo "  如需手动安装包: pip install <package> $PIP_INDEX_OPTION"
    fi
    
elif [ "$DEPLOY_MODE" == "3" ]; then
    # Docker部署
    echo -e "${GREEN}[8/8] 安装Docker...${NC}"
    
    if ! command -v docker &> /dev/null; then
        curl -fsSL https://get.docker.com | sh
        systemctl start docker
        systemctl enable docker
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
    fi
    
    echo -e "${GREEN}Docker安装完成${NC}"
    echo ""
    echo -e "${YELLOW}启动服务:${NC}"
    echo "  cd $APP_DIR"
    echo "  docker-compose up -d"
fi

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  所有配置完成！${NC}"
echo -e "${GREEN}========================================${NC}"

